<!--店铺管理-->
<script setup lang="ts">
  import {AxiosPromise} from "axios";
  import lodash from 'lodash-es'

  defineOptions({
    name: "StoreAccount",
    inheritAttrs: false,
  });

  import {
    getStoreAccountPage,
    getStoreAccountForm,
    saveStoreAccount,
    deleteStoreAccount,
  } from "@/api/storeAccount";

  import { StoreAccountQuery, StoreAccountForm } from "@/api/storeAccount/types";
  import {listAll} from "@/api/store";
  import {StoreForm, StoreVO} from "@/api/store/types";
  import {getDictOptions, getDictRemark} from "@/api/dict";

  const queryFormRef = ref(ElForm);
  const dataFormRef = ref(ElForm);

  const loading = ref(false);
  const ids = ref<number[]>([]);
  const total = ref(0);
  const storeList = ref<StoreForm[]>();
  const storeOptions = ref<StoreVO[]>();
  const platformDictList = ref<OptionType[]>();
  const platformName = ref('')
  const billTypeList = ref<[]>([])
	const storeKey = ref('')

  const queryParams = reactive<StoreAccountQuery>({
    pageNum: 1,
    pageSize: 20,
  });

  const storeAccountList = ref<[]>();

  const dialog = reactive<DialogOption>({
    visible: false,
  });

  const formData = reactive<StoreAccountForm>({});

  const rules = reactive({
    accountType: [{ required: true, message: "请选择账号类型", trigger: "change" }],
    account: [{ required: true, message: "请输入店铺账号", trigger: "blur" }],
    userName: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
    pwd: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
		voucher: [{ required: true, message: "请输入凭证KEY", trigger: "blur" }],
    commercePlatformStoreCode: [{ required: true, message: "请选择电商平台店铺名称", trigger: "change" }],
    // virtualAccountName: [{ required: true, message: "请选择虚拟账户名称", trigger: "blur" }],
    // needMoneyAccount: [{ required: true, message: "请选择是否是资金账户", trigger: "change" }],
  });

  /**
   * 查询
   */
  function handleQuery() {
    loading.value = true;
    getStoreAccountPage(queryParams)
            .then(({ data }) => {
              storeAccountList.value = data.list;
              total.value = data.total;
            })
            .finally(() => {
              loading.value = false;
            });
  }

  /**
   * 重置查询
   */
  function resetQuery() {
    queryFormRef.value.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /**
   * 行checkbox change事件
   */
  function handleSelectionChange(selection: any) {
    ids.value = selection.map((item: any) => item.id);
  }

  /**
   * 字典类型表单提交
   */
  function handleSubmit() {
    dataFormRef.value.validate((isValid: boolean) => {
      if (isValid) {

        loading.value = false;
        loading.value = true;
        saveStoreAccount(formData)
					.then(() => {
						ElMessage.success("保存成功");
						closeDialog();
						handleQuery();
					})
					.finally(() => (loading.value = false));
      }
    });
  }

  /**
   * 打开字典类型表单弹窗
   *
   * @param dicTypeId 字典类型ID
   */
  async function openDialog(id?: number) {
    await getAllStore()
		await getDictOptionList()
    dialog.visible = true;
    if (id) {
      dialog.title = "修改店铺账号";
      getStoreAccountForm(id).then(({ data }) => {
        Object.assign(formData, data);
				if (formData.commercePlatformStoreCode !== undefined) {
					const store = lodash.find(storeList.value, (store: StoreForm) => store.commercePlatformStoreCode === formData.commercePlatformStoreCode)
					platformName.value = getDictName(store.storeKey)
				}
      });
    } else {
      dialog.title = "新增店铺账号";
    }
  }

  /**
   * 关闭弹窗
   */
  function closeDialog() {
    dialog.visible = false;
    resetForm();
  }

  /**
   * 重置表单
   */
  function resetForm() {
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();

    formData.id = undefined;
	  platformName.value = ''
  }

  async function getAllStore() {
    listAll().then((response) => {
			storeOptions.value = []
			storeList.value = response.data;
			const group_store = lodash.groupBy(storeList.value, 'storeKeyName');
			for (let key in group_store) {
				storeOptions.value.push({'label': key, 'options': group_store[key]})
			}
    })
  }

  /**
   * 删除事件
   */
  function handleDelete(dictTypeId?: number) {
    const dictTypeIds = [dictTypeId || ids.value].join(",");
    if (!dictTypeIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      deleteStoreAccount(dictTypeIds).then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    });
  }

  const dictDataDialog = reactive<DialogOption>({
    visible: false,
  });

  /**
   * 获取字典类型的数据项
   *
   * @param typeCode 字典类型编码
   */
  async function getDictOptionList() {
	  getDictOptions('platform').then((response) => {
		  platformDictList.value = response.data;
	  });
  }

  function getDictName(key?: string) {
	  if (platformDictList != undefined) {
		  if (platformDictList.value != undefined) {
			  for (let dict of platformDictList.value) {
				  if (dict != undefined && dict.value+'' == key) {
					  return dict.label
				  }
			  }
		  }
	  }
	  return ''
  }

  function changeStore(commercePlatformStoreCode: string) {
		const store = lodash.find(storeList.value, (store: StoreForm) => store.commercePlatformStoreCode === commercePlatformStoreCode)
	  platformName.value = getDictName(store.storeKey)
		storeKey.value = store.storeKey
		billTypeList.value = []
		formData.accountType = undefined
		handleGetDictRemark()
	}

	function handleGetDictRemark() {
		getDictRemark(storeKey.value).then((response) => {
			billTypeList.value = response.data
		})
	}

  onMounted(() => {
    handleQuery();
  });
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="电商平台店铺编码/店铺标识" prop="keywords">
          <el-input
                  v-model="queryParams.keywords"
                  placeholder="电商平台店铺编码/店铺标识"
                  clearable
                  @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
          ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button
                v-hasPerm="['sys:storeAccount:save']"
                type="success"
                @click="openDialog()"
        ><i-ep-plus />新增</el-button
        >
        <el-button
                type="danger"
								v-hasPerm="['sys:storeAccount:delete']"
                :disabled="ids.length === 0"
                @click="handleDelete()"
        ><i-ep-delete />删除</el-button
        >
      </template>
      <el-table
              size="small"
              :header-row-style="{color: 'dimgray'}"
              v-loading="loading"
              highlight-current-row
              :data="storeAccountList"
							:height="storeAccountList && storeAccountList.length > 0 ? 570 : 130"
              border
              @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="平台" show-overflow-tooltip prop="platformName"/>
        <el-table-column label="电商平台店铺名称" show-overflow-tooltip prop="commercePlatformStoreName"/>
        <el-table-column label="账单类型" show-overflow-tooltip prop="accountType"/>
        <el-table-column label="凭证KEY" show-overflow-tooltip prop="voucher"/>
        <el-table-column label="店铺标识" show-overflow-tooltip prop="account"/>
        <el-table-column label="关联手机号" show-overflow-tooltip prop="mobile"/>
        <el-table-column label="短信验证码关键字" show-overflow-tooltip prop="messageKey"/>
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template #default="scope">
            <el-button
                    v-hasPerm="['sys:storeAccount:save']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="openDialog(scope.row.id)"
            ><i-ep-edit />编辑</el-button
            >
            <el-button
                    v-hasPerm="['sys:storeAccount:delete']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="handleDelete(scope.row.id)"
            ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            width="500px"
            :close-on-click-modal="false"
            @close="closeDialog"
    >
      <el-form
              ref="dataFormRef"
              :model="formData"
              :rules="rules"
              label-width="150px"
      >
        <el-form-item label="电商平台店铺名称" prop="commercePlatformStoreCode">
          <el-select class="yz-el-select" v-model="formData.commercePlatformStoreCode" filterable @change="changeStore" placeholder="请选择电商平台店铺名称">
						<el-option-group
								v-for="group in storeOptions"
								:key="group.label"
								:label="group.label"
						>
							<el-option
									v-for="item in group.options"
									:key="item.id"
									:label="item.commercePlatformStoreName"
									:value="item.commercePlatformStoreCode"
							/>
						</el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="账单类型" prop="accountType">
					<el-select class="yz-el-select" v-model="formData.accountType" filterable placeholder="请选择账单类型">
						<el-option v-for="item in billTypeList" :key="item" :label="item" :value="item" >
						</el-option>
					</el-select>
        </el-form-item>
        <el-form-item label="凭证KEY" prop="voucher">
          <el-input v-model="formData.voucher" placeholder="请输入凭证KEY" clearable/>
        </el-form-item>
        <el-form-item label="店铺标识" prop="account">
          <el-input v-model="formData.account" placeholder="请输入店铺标识" clearable/>
        </el-form-item>
        <el-form-item label="关联手机号" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入关联手机号" clearable/>
        </el-form-item>
        <el-form-item label="短信验证码关键字" prop="messageKey">
					<el-input v-model="formData.messageKey" placeholder="请输入关联手机号" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
